
package c.x.jy.api.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;

import c.x.jy.api.utils.HttpContextUtils;
import c.x.jy.api.utils.JwtUtils;
import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.GetClassinfo;
import c.x.jy.dao.entity.BusinessEntity;
import c.x.jy.dao.entity.SysUserEntity;
import c.x.jy.service.service.BusinessService;
import c.x.jy.service.service.ShiroService;
import c.x.jy.service.service.SysUserService;
import c.x.jy.service.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * Controller公共组件
 *
 * 
 */
@Slf4j
public abstract class AbstractController {

	protected SysUserEntity getUser() {// getPrincipals
		HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
		// 获取用户凭证
		String token = request.getHeader(JwtUtils.jwtUtils.getHeader());
		if (StringUtils.isBlank(token)) {
			token = request.getParameter(JwtUtils.jwtUtils.getHeader());
		}
		Long userid = JwtUtils.jwtUtils.getLoginUserId(token);
		if (userid == null) {
			throw new RRException("登陆失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}
		SysUserEntity userentity = SpringContextUtils.getBean(SysUserService.class).selectCacheById(userid);

		SysUserEntity user = null;

		if (userentity != null) {
			userentity.setPassword(null);
			userentity.setSalt(null);
			user = new SysUserEntity();
			GetClassinfo.ObjectChangeToObject(userentity, user);
 
			if (user.getBusinessId().equals(0)) {
				throw new RRException("小程序未绑定商家不能登陆！");
			} else {
				BusinessEntity business = SpringContextUtils.getBean(BusinessService.class) .selectBusinessById(user.getBusinessId());
			//	if (business.getType().equals(BusinessEntity.TypeEum.platform.getValue())) {
				//	user.setPlatformId(business.getId());
			//	} else {
					user.setPlatformId(business.getPlatformId());
			//	}
			 	user.setBusinesstype(business.getType());
			}

			// user.setRoles(SpringContextUtils.getBean(SysRoleService.class).selectRolesByUserId(user.getUserId()));
			user.setPermissions(SpringContextUtils.getBean(ShiroService.class).getUserPermissions(user.getUserId()));
		}
		return user;
	}

	protected Long getUserId() {

		return getUser().getUserId();
	}

	protected Long getPlatformId() {

		return getUser().getPlatformId();
	}

}
